package com.youdoneed.friends.recommanderFacePicture;

import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import com.querydsl.sql.dml.SQLUpdateClause;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.GlobalIdWorker;
import com.youdoneed.base.pagination.Page;
import com.youdoneed.base.pagination.Paging;
import com.youdoneed.friends.application.QueryHelper;
import com.youdoneed.friends.model.RecommandFacePicture;
import com.youdoneed.friends.query.QRecommandFacePicture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Created by lid on 2017/11/21 0021.
 */
@Service
@Transactional
public class RecommandFacePictureService {

    private static final String DIRECTIONUP = "up";

    private static final String DIRECTIONDOWN = "down";

    private final Logger logger = LoggerFactory.getLogger(RecommandFacePictureService.class);

    @Autowired
    private SQLQueryFactory queryFactory;

    private QRecommandFacePicture qRecommandFacePicture = QRecommandFacePicture.RecommandFacePicture;

    public RecommandFacePicture getFacePictureById(String facePictureId) {
        if (!StringUtils.hasText(facePictureId)) {
            throw new AppException("facePictureId为空!");
        }

        return queryFactory.selectFrom(qRecommandFacePicture)
                .where(qRecommandFacePicture.facePictureId.eq(facePictureId))
                .fetchOne();
    }

    public Page<RecommandFacePicture> getAllPicturesByPage(Paging paging) {
        SQLQuery<RecommandFacePicture> query = queryFactory.selectFrom(qRecommandFacePicture)
                .orderBy(qRecommandFacePicture.sort.asc());
        return QueryHelper.queryPage(paging, query);
    }

    public void addPicture(String pictureUrl, String mark) {
        if (!StringUtils.hasText(pictureUrl)) {
            throw new AppException("图片地址链接为空!");
        }

        RecommandFacePicture picture = new RecommandFacePicture();
        picture.setCreateDate(new Date());
        picture.setFacePictureId(GlobalIdWorker.nextString());
        picture.setFacePictureUrl(pictureUrl);
        if (StringUtils.hasText(mark)) {
            picture.setMark(mark);
        }
        Integer sort = queryFactory.select(qRecommandFacePicture.sort)
                .from(qRecommandFacePicture)
                .orderBy(qRecommandFacePicture.sort.desc())
                .limit(1)
                .fetchOne();
        if (null == sort) {
            picture.setSort(1);
        } else {
            picture.setSort(sort + 1);
        }
        queryFactory.insert(qRecommandFacePicture).populate(picture).execute();
    }

    public void deletePicture(String facePictureId) {
        queryFactory.delete(qRecommandFacePicture).where(qRecommandFacePicture.facePictureId.eq(facePictureId)).execute();
    }

    public void updatePicture(String facePictureId, String pictureUrl, String mark) {
        if (!StringUtils.hasText(facePictureId)) {
            throw new AppException("facePictureId为空!");
        }

        if ((!StringUtils.hasText(pictureUrl))
                && (!StringUtils.hasText(mark))) {
            return;
        }

        RecommandFacePicture upDatePicture = new RecommandFacePicture();
        if (StringUtils.hasText(pictureUrl)) {
            upDatePicture.setFacePictureUrl(pictureUrl);
        }

        if (StringUtils.hasText(mark)) {
            upDatePicture.setMark(mark);
        }
        SQLUpdateClause update = queryFactory.update(qRecommandFacePicture)
                .populate(upDatePicture)
                .where(qRecommandFacePicture.facePictureId.eq(facePictureId));

        update.execute();
    }

    public void changeSort(String facePictureId, String direction) {
        if (!StringUtils.hasText(facePictureId)) {
            throw new AppException("facePictureId为空!");
        }

        if (!StringUtils.hasText(direction)) {
            throw new AppException("方向为空!");
        }

        RecommandFacePicture recommandFacePicture = this.getFacePictureById(facePictureId);

        if (RecommandFacePictureService.DIRECTIONUP.equals(direction)) {
            //向上
            RecommandFacePicture lastOne = queryFactory.selectFrom(qRecommandFacePicture)
                    .where(qRecommandFacePicture.sort.lt(recommandFacePicture.getSort()))
                    .orderBy(qRecommandFacePicture.sort.desc())
                    .fetchFirst();

            if (null == lastOne) {
                throw new AppException("已经到顶了！");
            }

            this.swapSort(recommandFacePicture, lastOne);
        }

        if (RecommandFacePictureService.DIRECTIONDOWN.equals(direction)) {
            RecommandFacePicture lastOne = queryFactory.selectFrom(qRecommandFacePicture)
                    .where(qRecommandFacePicture.sort.gt(recommandFacePicture.getSort()))
                    .orderBy(qRecommandFacePicture.sort.asc())
                    .fetchFirst();

            if (null == lastOne) {
                throw new AppException("已经到底了！");
            }
            this.swapSort(recommandFacePicture, lastOne);
        }
    }

    /**
     * 交换顺序。
     */
    public long swapSort(RecommandFacePicture pictureA, RecommandFacePicture pictureB) {
        SQLUpdateClause update = queryFactory.update(qRecommandFacePicture);
        update.set(qRecommandFacePicture.sort, pictureA.getSort())
                .where(qRecommandFacePicture.facePictureId.eq(pictureB.getFacePictureId()))
                .addBatch();
        update.set(qRecommandFacePicture.sort, pictureB.getSort())
                .where(qRecommandFacePicture.facePictureId.eq(pictureA.getFacePictureId()))
                .addBatch();
        return update.execute();
    }
}
